/**
 * Malsha Sewwandi 2014-06-26
 */

Rollover = new Object();
var rolloverType = null;
var dealTypeValue = null;
var dealStore = Ext.create('Ext.data.Store', {
	fields : [ 'dealCode', 'fund', 'issuer', 'dealValue', 'maturityDate', 'maturityValue', 'dealType', 'instumentType', 'rolloverValue', 'balance', 'rolloverDealtype' ]
});

var deal_type_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'code', 'dealType', 'description', 'rollover', 'shortMaturity' ],
});

var repodata = [ {
	dealCode : '00001',
	fund : "High Yield Fund",
	issuer : "Issuer1",
	dealValue : '1000502',
	maturityDate : Ext.Date.parse("27/06/2014", "d/m/Y"),
	maturityValue : '1200502',
	dealType : 'R'
}, {
	dealCode : '00002',
	fund : "Investment Grade Fund",
	issuer : "Issuer2",
	dealValue : '1065891',
	maturityDate : Ext.Date.parse("30/06/2014", "d/m/Y"),
	maturityValue : '1565891',
	dealType : 'FD'
}, {
	dealCode : '00003',
	fund : "Gilt Fund",
	issuer : "Issuer3",
	dealValue : '15896344',
	maturityDate : Ext.Date.parse("03/07/2014", "d/m/Y"),
	maturityValue : '20356874',
	dealType : 'RR'
}, {
	dealCode : '00009',
	fund : "Investment Grade Fund",
	issuer : "Issuer4",
	dealValue : '4896548',
	maturityDate : Ext.Date.parse("01/07/2014", "d/m/Y"),
	maturityValue : '45154400',
	dealType : 'R'
}, {
	dealCode : '00008',
	fund : "Gilt Fund",
	issuer : "Issuer4",
	dealValue : '464464',
	maturityDate : Ext.Date.parse("01/07/2014", "d/m/Y"),
	maturityValue : '5154400',
	dealType : 'P',
	instumentType : 'T'
}, {
	dealCode : '00007',
	fund : "Gilt Fund",
	issuer : "Issuer4",
	dealValue : '4896548',
	maturityDate : Ext.Date.parse("03/07/2014", "d/m/Y"),
	maturityValue : '44544663',
	dealType : 'P',
	instumentType : 'T'
}, {
	dealCode : '00006',
	fund : "High Yield Fund",
	issuer : "Issuer3",
	dealValue : '4896548',
	maturityDate : Ext.Date.parse("02/07/2014", "d/m/Y"),
	maturityValue : '8445464',
	dealType : 'P',
	instumentType : 'T'
}, {
	dealCode : '00005',
	fund : "High Yield Fund",
	issuer : "Issuer 2",
	dealValue : '565666',
	maturityDate : Ext.Date.parse("01/07/2014", "d/m/Y"),
	maturityValue : '7797944',
	dealType : 'P',
	instumentType : 'TB'
}, {
	dealCode : '00004',
	fund : "Gilt Fund",
	issuer : "Issuer1",
	dealValue : '489652',
	maturityDate : Ext.Date.parse("01/07/2014", "d/m/Y"),
	maturityValue : '458922300',
	dealType : 'P',
	instumentType : 'TB'
} ];

Rollover.getCenterPanel = function() {
	
	var deal_type_store = Ext.create('Ext.data.Store', {
		fields : [ 'id', 'code', 'dealType', 'description', 'rollover', 'shortMaturity' ],
	});

	var dealStore = Ext.create('Ext.data.Store', {
		fields : [
		          { name : 'id',				typr : 'int',		},
		          { name : 'dealCode',			type : 'string',	},
		          { name : 'fund',				type : 'string',	},
		          { name : 'issuer',			type : 'string',	},
		          { name : 'dealValue',			type : 'float',		},
		          { name : 'maturityDate',		type : 'date', 		dateFormat : 'c',	}, //d/m/Y
		          { name : 'maturityValue',		type : 'float',		},
		          { name : 'dealType',			type : 'string',	},
		          { name : 'instumentType',		type : 'string',	},
		          { name : 'rolloverValue',		type : 'float',		},
		          { name : 'balance',			type : 'float',		},
		          { name : 'rolloverDealtype',	type : 'string',	}
		         ],
		storeId:'rollOverDealStore',	          
	});
	
	
	var instrumentTypeStore = new Ext.data.Store({
		fields : [
		          {		name : 'id',				type : 'int'		},
		          {		name : 'instrumentName',	type : 'string'		},
		          {		name : 'istrumentType',		type : 'int'		}
		         ]
	});

	Ext.Ajax.request({
		url : 'getInstrumentTypes.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			instrumentTypeStore.loadRawData(obj.instrumentTypeList);
			instrumentTypeStore.add({id : 0,	instrumentName : 'All Instrument Types',	istrumentType : 2 });
		}
	});
	
	var dealGrid = Ext.create('Ext.grid.Panel', {
		title : 'Deals',
		store : dealStore,
		anchor : '100%',
		id : 'rollOverDealsGrid',
		emptyText : '<B>No records found<B>',
		columns : [
		{
			text : 'Code',
			dataIndex : 'dealCode',
			flex : 3
		},
		{
			text : 'Fund',
			dataIndex : 'fund',
			flex : 2
		}, {
			text : 'Issuer',
			dataIndex : 'issuer',
			flex : 2,
			//hidden : true,
		}, {
			text : 'Deal Value',
			dataIndex : 'dealValue',
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			flex : 3
		}, {
			header : 'Maturity Date',
			xtype : 'datecolumn',
			format : 'd/m/Y',
			align : 'center',
			dataIndex : 'maturityDate',
			width : 80
		}, {
			text : 'Maturiry Value',
			xtype : 'numbercolumn',
			dataIndex : 'maturityValue',
			format : '0,000.0000',
			align : 'right',
			flex : 3
		}, {
			text : 'Rollover Value',
			xtype : 'numbercolumn',
			dataIndex : 'rolloverValue',
			format : '0,000.0000',
			align : 'right',
			minValue : 0,
			flex : 3,
			getEditor : function(record) {
				if (rolloverType == 'P') {
					return Ext.create('Ext.grid.CellEditor', {
						field : {
							xtype : 'numberfield',
							decimalPrecision : 4,
							hideTrigger : true,
							keyNavEnabled : false,
							msgTarget : 'side',
							mouseWheelEnabled : false,
							listeners : {
								blur : function(field, e) {
									var selection = dealGrid.getView().getSelectionModel().getSelection()[0];
									if (selection) {
										if (field.value != null & field.value > 0) {
											var maturity = selection.get('maturityValue');
											var enterdValue = field.value;
											selection.set('balance', maturity - enterdValue);
										}
									}
								}
							}
						}
					});
				} else {
					return false;
				}
			}
		}, {
			text : 'Balance',
			xtype : 'numbercolumn',
			dataIndex : 'balance',
			format : '0,000.0000',
			align : 'right',
			flex : 3
		}, {
			text : 'RolloverType',
			dataIndex : 'rolloverDealtype',
			align : 'center',
			width : 100,
			editor : {
				xtype : 'combo',
				displayField : 'name',
				valueField : 'value',
				store : Ext.create('Ext.data.Store', {
					fields : [ 'name', 'value' ],
					data : [ {
						name : 'Purchases',
						value : 'PURCH',
					}, {
						name : 'Repo',
						value : 'REPO',
					}, {
						name : 'Fixed Deposits',
						value : 'FD',
					}, {
						name : 'Reverse Repo',
						value : 'RREPO',
					} ]
				}),
			},
		}, {
			xtype : 'actioncolumn',
			width : 36,
			align : 'center',
			items : [ {
				icon : 'images/Go_1.jpg',
				tooltip : 'Click for go to Deal Screen',
				handler : function(grid, rowIndex, colIndex) {
					if (dealTypeValue != null) {
						var rec = grid.getStore().getAt(rowIndex);
						
						if (rec.get('rolloverDealtype') != "") {							
							var rAllowed = false;
							
							if(rec.get('dealType')==='REPO'){
								if(rec.get('rolloverDealtype')==='REPO'){
									rAllowed = true;
								}else{
									Ext.Msg.alert('Error', 'REPO Deal cannot be RolledOver to '+rec.get('rolloverDealtype'));
									rAllowed = false;
								}
							}else{
								if(rec.get('rolloverDealtype')==='REPO'){
									Ext.Msg.alert('Error', rec.get('dealType') + ' Deal cannot be RolledOver to REPO');
									rAllowed = false;
								}else{
									rAllowed = true;
								}
							}
							if(rAllowed === true){
								rAllowed=false;
								Ext.Ajax.request({
									url : 'queryFundByCode.action',
									params : {
										queryOne : rec.get('fund'),
									},
									success : function(response) {
										var obj = Ext.decode(response.responseText);
										var arrayLength = obj.fund.dealTypes.length;
										for (var i = 0; i < arrayLength; i++) {
											if(obj.fund.dealTypes[i].code===rec.get('rolloverDealtype')){
												rAllowed = true;
												break;
											}
										}
										if(rAllowed===false){
											Ext.Msg.alert('Error', rec.get('rolloverDealtype') + ' deals are not allowed with Fund: '+rec.get('fund'));
										}else if(rAllowed===true && rec.get('rolloverDealtype')==='FD'){
											rAllowed = false;
											arrayLength = obj.fund.issures.length;
											for (var i = 0; i < arrayLength; i++) {
												if(obj.fund.issures[i].code===rec.get('issuer')){
													rAllowed = true;
													break;
												}
											}											
											if(rAllowed===false){
												Ext.Msg.alert('Error', rec.get('issuer') + ' is not allowed for FD deals with Fund: '+rec.get('fund'));
											}
										}
										
										
										if(rAllowed===true){
											if (rolloverType == 'P') {
												if (rec.get('rolloverValue') != null & rec.get('rolloverValue') > 0) {
													if (rec.get('rolloverDealtype') == 'PURCH') {
														//instumentType
														//App.Core.setScreen(PurchasesDeal.getCenterPanel());
														App.Core.setScreen(PurchasesDeal.getRollOverDeal(rec.get('instumentType'), rec.get('fund'), rec.get('dealCode'), rec.get('issuer'), rec.get('maturityDate'), rec.get('rolloverValue')));
													} else if (rec.get('rolloverDealtype') == 'REPO') {
														App.Core.setScreen(RepoDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('rolloverValue')));
													} else if (rec.get('rolloverDealtype') == 'FD') {
														//App.Core.setScreen(FDDeal.getCenterPanel());
														App.Core.setScreen(FDDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('dealCode'), rec.get('maturityDate'), rec.get('rolloverValue')));
														//FDDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('rolloverValue'));
													} else if (rec.get('rolloverDealtype') == 'RREPO') {
														//App.Core.setScreen(ReverseRepoDeal.getCenterPanel());
														App.Core.setScreen(ReverseRepoDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('rolloverValue')));
													}
													dealTypeValue = null;
													rolloverType = null;
													dealStore.removeAll();
													//this.up('form').getForm().reset();
												} else {
													Ext.Msg.alert('Failed', 'Plase Enter Rollover value');
												}
											} else {
												if (rec.get('rolloverDealtype') == 'PURCH') {
													//App.Core.setScreen(PurchasesDeal.getCenterPanel());
													App.Core.setScreen(PurchasesDeal.getRollOverDeal(rec.get('instumentType'), rec.get('fund'), rec.get('dealCode'), rec.get('issuer'), rec.get('maturityDate'), rec.get('maturityValue')));
												} else if (rec.get('rolloverDealtype') == 'REPO') {
													App.Core.setScreen(RepoDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('maturityValue')));
												} else if (rec.get('rolloverDealtype') == 'FD') {
													//App.Core.setScreen(FDDeal.getCenterPanel());
													App.Core.setScreen(FDDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('dealCode'), rec.get('maturityDate'), rec.get('maturityValue')));
													//FDDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('maturityValue'));
												} else if (rec.get('rolloverDealtype') == 'RREPO') {
													//App.Core.setScreen(ReverseRepoDeal.getCenterPanel());
													//ReverseRepoDeal
													App.Core.setScreen(ReverseRepoDeal.getRollOverDeal(rec.get('fund'), rec.get('issuer'), rec.get('maturityDate'), rec.get('maturityValue')));
												}
												dealTypeValue = null;
												rolloverType = null;
												dealStore.removeAll();
												//this.up('form').getForm().reset();
											}								
										}
									},
									failure : function(response){
										Ext.Msg.alert('Error!', 'Failed to veryfy with Fund : '+response);
									},
								});															
							}
							
						} else {
							Ext.Msg.alert('Failed', 'Plase Select the Rollover Deal Type');
						}
					} else {
						Ext.Msg.alert('Failed', 'Plase Select the Deal Type');
					}
				}
			} ]
		} ],
		plugins : [ Ext.create('Ext.grid.plugin.CellEditing', {
			clicksToEdit : 1
		}) ],
		height : 380,
	});

	var formPanel =  Ext.create('Ext.form.Panel', {
		title : 'Maturities Rollover',
		bodyPadding : '20',
		autoScroll : true,
		defaults : {
			labelWidth : 200,
			anchor : '65%'
		},
		frame : true,
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Deal Type',
				id : 'rollOverDealTypeCmb',
				width : 254,
				padding : '0 15 0 0',
				displayField : 'dealType',
				valueField : 'code',
				queryMode : 'local',
				isLoaded : false,
				allowBlank : false,
				store : deal_type_store,
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getRolloverDealType.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.dealTypeDtos);
									combo.isLoaded = true;
								}
							});
						}
					},
					select : onDealTypeSelect
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Instrument Type',
				hidden : true,
				width : 254,
				id : 'rollOverInsTypes',
				displayField : 'instrumentName',
				valueField : 'instrumentName',
				queryMode : 'local',
				value : 'All Instrument Types',
				store : instrumentTypeStore,
				listeners : {
					select : filter_purchases
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			labelWidth : 100,
			fieldLabel : 'Maturity Date',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'From',
				id : 'rollOverFromDate',
				width : 150,
				labelWidth : 30,
				padding : '0 15 0 0',
				disabledDays : [ 0, 6 ],
				value : new Date(),
				listeners : {
					'change' : filterDeals
				}
			}, {
				xtype : 'datefield',
				fieldLabel : 'To',
				id : 'rollOverToDate',
				labelWidth : 20,
				width : 150,
				disabledDays : [ 0, 6 ],
				value : new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 7),
				listeners : {
					'change' : filterDeals
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			labelWidth : 100,
			fieldLabel : 'Rollover Type',
			defaultType : 'radiofield',
			items : [ {
				boxLabel : 'Full',
				name : 'rollover',
				inputValue : 'F',
				id : 'radio1',
				checked : true,
				padding : '0 15 0 0'
			}, {
				boxLabel : 'Partial / Over',
				name : 'rollover',
				inputValue : 'P',
				id : 'radio2',
				listeners : {
					change : function(field, newValue, oldValue) {
						if (newValue) {
							rolloverType = field.inputValue;
						} else {
							rolloverType = null;
						}
					}
				}
			} ]
		}, dealGrid ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				dealTypeValue = null;
				dealStore.removeAll();
				this.up('form').getForm().reset();
			}
		} ]
	});
	
	Ext.Ajax.request({
		url : 'getRolloverDealType.action',
		success : function(response) {
			var dealTypeCmb = Ext.ComponentQuery.query('#rollOverDealTypeCmb')[0];
			var obj = Ext.decode(response.responseText);
			dealTypeCmb.getStore().loadRawData(obj.dealTypeDtos);
			dealTypeCmb.isLoaded = true;
		}
	});
	
	return formPanel;
};

function onDealTypeSelect(combo, record, index) {
	dealTypeValue = combo.getValue();
	Ext.getCmp('rollOverInsTypes').setValue('All Instrument Types');
	var loadingMask = Ext.getCmp('rollOverDealsGrid');
	loadingMask.setLoading('Loading Deals...', true);
	var tmpDealsStore = Ext.data.StoreManager.lookup('rollOverDealStore');
	tmpDealsStore.clearFilter(true);
	tmpDealsStore.removeAll();
	
	if (dealTypeValue != null) {	
		Ext.Ajax.request({
			url : 'getConfDealsByType.action',
			params : {
				dealTypeCode : dealTypeValue,
			},
			success : function(response) {
				var insType = null;
				var obj = Ext.decode(response.responseText);
				var arrayLength = obj.dealList.length;
				for (var i = 0; i < arrayLength; i++) {
					if(obj.dealList[i].dealType.code==='PURCH'){
						insType = obj.dealList[i].dealInstrumentMaps[0].instrument.instrumentType.instrumentName;
					}else{
						insType = null;
					}				
					tmpDealsStore.add(
				    		{
				    			id				: obj.dealList[i].id,
				    			dealCode		: obj.dealList[i].dealCode,
				    			fund			: obj.dealList[i].fund.fundCode,
				    			issuer			: obj.dealList[i].issuer.code,
				    			dealValue		: obj.dealList[i].dealValue,
				    			maturityDate	: obj.dealList[i].maturityDate,
				    			maturityValue	: obj.dealList[i].maturityValue,
				    			dealType		: obj.dealList[i].dealType.code,
				    			instumentType	: insType,
				    		});
				}
				
				filterDeals();
				loadingMask.setLoading(false);
			},
			failure : function(){
				loadingMask.setLoading(false);
				Ext.Msg.alert('Error', 'Failed to Load Deal List');
			}
		});
		
		if(dealTypeValue==='PURCH'){
			Ext.getCmp('rollOverInsTypes').show();
		}else{
			Ext.getCmp('rollOverInsTypes').hide();
		}
	}
	/*setTimeout(function(target) {
		target.setLoading(false);
	}, 2000, loadingMask);*/
}

function filter_purchases(combo, record, index) {
	
	filterDeals();
	
	
	
	/*	
	tmpDealsStore.filter([ {
		property : 'instumentType',
		value : instumentType,
	}, {
		filterFn : function(item) {
			return item.get("instumentType") === instumentType;
		}
	} ]);

	if (instumentType == 'T') {
		dealStore.clearFilter(true);
		dealStore.filter([ {
			property : 'instumentType',
			value : "T"
		}, {
			filterFn : function(item) {
				return item.get("instumentType") == 'T';
			}
		} ]);
		dealStore.loadData(repodata, false);
	} else if (instumentType == 'CP') {
		dealStore.clearFilter(true);
		dealStore.filter([ {
			property : 'instumentType',
			value : "CP"
		}, {
			filterFn : function(item) {
				return item.get("instumentType") == 'CP';
			}
		} ]);
		dealStore.loadData(repodata, false);
	} else if (instumentType == 'TB') {
		dealStore.clearFilter(true);
		dealStore.filter([ {
			property : 'instumentType',
			value : "TB"
		}, {
			filterFn : function(item) {
				return item.get("instumentType") == 'TB';
			}
		} ]);
		dealStore.loadData(repodata, false);
		}*/
}


function filterDeals() {
	var fromDt = Ext.ComponentQuery.query('#rollOverFromDate')[0].getValue();
	var toDt = Ext.ComponentQuery.query('#rollOverToDate')[0].getValue();
	var dealType = Ext.ComponentQuery.query('#rollOverDealTypeCmb')[0].getValue();
	var insType = null;
	if(dealType=='PURCH'){
		insType = Ext.ComponentQuery.query('#rollOverInsTypes')[0].getValue();	
	}
	var tmpDealsStore = Ext.data.StoreManager.lookup('rollOverDealStore');
	tmpDealsStore.clearFilter(true);
	
	tmpDealsStore.filter([
	                      {filterFn: function(item) {
	                    	  if(fromDt!=null){
	                    		  if(item.get("maturityDate")<fromDt){
	                    			  return false;
	                    		  }
	                    	  }
	                    	  if(toDt!=null){
	                    		  if(item.get("maturityDate")>toDt){
	                    			  return false;
	                    		  }
	                    	  }
	                    	  if(dealType=='PURCH' && insType!=null && insType!='All Instrument Types'){
	                    		  if(item.get("instumentType")!==insType){
	                    			  return false;
	                    		  }
	                    	  }	                    	  
	                    	  return true; }}
	                     ]);	
	
}
